#include "SavingsAccount.hh"
#include "Customer.hh"
#include "CheckingAccount.hh"
#include "Utilities.hh"
#include "main.hh"
#include <iostream>
#include <algorithm>

SavingsAccount::SavingsAccount(const std::string& id, Customer* holder, double initialBalance)
    : Account(id, holder, initialBalance, "Savings") {}

void SavingsAccount::deposit(double amount, const std::string& note) {
    if (amount <= 0) {
        std::cout << "Error: Deposit amount must be positive.\n";
        return;
    }

    balance += amount;
    addTransaction(amount, "Deposit", note);
    std::cout << "Deposit successful!\n";
    std::cout << "New balance: " << Utilities::formatCurrency(balance) << "\n";
}

void SavingsAccount::withdraw(double amount, const std::string& note) {
    std::cout << "Error: Withdrawals are not allowed from savings accounts.\n";
}

void SavingsAccount::transfer(Account* destination, double amount, const std::string& note) {
    if (!destination) {
        std::cout << "Error: Destination account is invalid.\n";
        return;
    }

    if (amount <= 0) {
        std::cout << "Error: Transfer amount must be positive.\n";
        return;
    }

    // Savings accounts can only transfer to checking accounts of the same customer
    if (destination->getAccountType() != "Checking" || 
        destination->getAccountHolder() != accountHolder) {
        std::cout << "Error: Savings accounts can only transfer to the account holder's checking account.\n";
        return;
    }

    if (amount > balance) {
        std::cout << "Error: Insufficient funds for transfer.\n";
        return;
    }

    balance -= amount;
    destination->deposit(amount, "Transfer from " + accountId + ": " + note);
    addTransaction(-amount, "Transfer to " + destination->getAccountId(), note);
    std::cout << "Transfer successful!\n";
    std::cout << "New balance: " << Utilities::formatCurrency(balance) << "\n";
}

void SavingsAccount::displayAccountInfo() const {
    std::cout << "\n===== Bank Account: " << accountId << " (" << accountType << " Account) =====\n";
    std::cout << "Account holder: " << accountHolder->getName() << "\n";
    std::cout << "Balance: " << Utilities::formatCurrency(balance) << "\n\n";
}